<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-11 15:35:21
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Models\ProEmployeePro;
use App\Models\ProProcessPro;
use App\Repositories\ClhzItemsViewRepository;
use App\Repositories\ClhzViewRepository;
use App\Repositories\ProEmployeeProRepository;
use App\Repositories\ProProcessesRepository;
use App\Repositories\ProProcessesPassRepository;
use App\Repositories\ProProcessesWipRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property ProProcessesPassRepository $pass
 * @property ProProcessesRepository $repository 
 * @property ClhzViewRepository $clhzview 
 * @property ClhzItemsViewRepository $clhzitems 
 * @author sunkaiyuan
 */
class ProcessesService extends Service
    {
    public function __construct(ProProcessesRepository $repository, ProProcessesPassRepository $pass, ClhzViewRepository $clhzview, ClhzItemsViewRepository $clhzitems)
        {
        $this->repository = $repository;
        $this->pass       = $pass;
        $this->clhzview   = $clhzview;
        $this->clhzitems  = $clhzitems;
        }

    protected function resetCl()
        {
        $request = request();
        $begin   = $request->begin;
        $end     = $request->end;
        ProEmployeeProRepository::where("billdate", ">=", $begin)->where("billdate", "<=", $end)->get()->filter(fn($v) => $v->delete());
        ProProcessPro::where("billdate", ">=", $begin)->where("billdate", "<=", $end)->get()->filter(fn($v) => $v->delete());
        $this->pass->where("swiped_at", ">=", $begin)->where("swiped_at", "<=", $end)->get()->map(function ($item)
            {
            if ($item->process->autopro == 1 && $item->direction_id == 1) {
                ProEmployeeProRepository::run("add", [
                    'employee_id'      => $item->swipor_id,
                    'quantity'         => $item->out_quantity,
                    'billdate'         => $item->swiped_at,
                    'route_process_id' => $item->route_process_id
                ]);
                }
            });
        }
    public function clhz()
        {
        // DB::enableQueryLog();
        $data = $this->clhzview->condition(request())->getGrid();
        return $data;
        }
    public function clhzitems()
        {
        // DB::enableQueryLog();
        $data = $this->clhzitems->condition(request())->getGrid(true, 'created_at', "desc");
        return $data;
        }
    public function list()
        {
        // DB::enableQueryLog();
        $data = $this->repository->condition(request())->orderBy("sort")->getGrid();

        return $data;
        }
    public function userclass()
        {
        // DB::enableQueryLog();
        $data = $this->repository->whereId(request("process_id"))->first()->position->users->pluck("shift");
        // dd(DB::getQueryLog());
        return $data;
        }
    public function user()
        {
        $QUERY = $this->repository->whereId(request("process_id"))->first()?->position?->users()->whereIs_fire(0);
        if (request()->has("shift_id"))
            $QUERY = $QUERY?->whereShift_id(request("shift_id"));
        return $QUERY?->orderBy("sort")->get() ?? [];
        }
    protected function remove()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->map(function ($item)
            {
            return $item->delete();
            });
        }
    public function pass_list()
        {
        return $this->pass->condition(request())->getGrid();
        }

    /**
     * 染色过数
     * @return mixed
     * @author sunkaiyuan
     */
    protected function swipe()
        {
        $request = request();

        return array_filter(is_array($request->details) ? $request->details : json_decode($request->details, true), function ($item) use ($request)
            {
            return $this->passswip(
                $item['id'],
                $item['faultle_quantity'],
                $item['rejects_quantity'] ?? 0,
                $request->direction_id ?? 1,
                $request->pro_dept_id ?? 0,
                $request->outfactory_id ?? 0,
                $request->swipor_id,
                $request->swiped_at ?? date('Y-m-d H:i:s'),
                $item['out_quantity'] ?? $item['faultle_quantity'],
                $request->location_id ?? 0,
                0,
                $request->remark ?? ""
            );
            });
        }

    protected function swipeone()
        {
        $request = request();
        $wip     = is_array($request->details) ? $request->details : json_decode($request->details, true);
        if (count($wip) == 1) {
            if (isEmpty($request->quantity)) {
                fail("正品数必填！");
                }
            if (!isEmpty($request->scrap_quantity) && isEmpty($request->defects)) {
                fail("疵点必须选！");
                }
            return array_filter($wip, function ($item) use ($request)
                {
                $pass_m = $this->passswip(
                    $item['id'],
                    $request->quantity,
                    isEmpty($request->scrap_quantity) ? 0 : $request->scrap_quantity,
                    $request->direction_id ?? 1,
                    $request->pro_dept_id ?? 0,
                    $request->outfactory_id ?? 0,
                    $request->swipor_id,
                    $request->swiped_at ?? date('Y-m-d H:i:s'),
                    $item['faultle_quantity'],
                    $request->location_id ?? 0,
                    $request->device_id ?? 0,
                    $request->remark ?? "",
                );

                $open_card_m          = $pass_m->open_card;
                $defects              = array_unique(array_merge(explode(",", $request->defects), explode(",", $open_card_m->defects)));
                $open_card_m->defects = implode(",", $defects);
                $open_card_m->save();
                });
            }
        else {
            return array_filter($wip, function ($item) use ($request)
                {
                $wip_m  = ProProcessesWipRepository::whereId($item['id'])->first();
                $pass_m = $this->passswip(
                    $item['id'],
                    $wip_m->faultle_quantity,
                    0,
                    $request->direction_id ?? 1,
                    $request->pro_dept_id ?? 0,
                    $request->outfactory_id ?? 0,
                    $request->swipor_id,
                    $request->swiped_at ?? date('Y-m-d H:i:s'),
                    $wip_m->faultle_quantity,
                    $request->location_id ?? 0,
                    $request->device_id ?? 0,
                    $request->remark ?? 0,
                );

                $open_card_m          = $pass_m->open_card;
                $defects              = array_unique(array_merge(explode(",", $request->defects), explode(",", $open_card_m->defects)));
                $open_card_m->defects = implode(",", $defects);
                $open_card_m->save();
                });
            }
        }
    //新增函数，用于别的接口调用时 rollback
    protected function passswip(
        $wip_id,
        $faultle_quantity,
        $rejects_quantity = 0,
        $direction_id = 1,
        $pro_dept_id = null,
        $factory_id = null,
        $swipor_id = null,
        $swiped_at = null,
        $out_quantity = null,
        $location_id = 0,
        $device_id = 0,
        $remark = ""
    ) {
        $pass = $this->pass->swipe($wip_id, $faultle_quantity, $rejects_quantity, $direction_id, $pro_dept_id, $factory_id, $swipor_id, $swiped_at, $out_quantity, $location_id, $device_id, $remark);

        $open_card_m = $pass->open_card;
        $open_card_m->scheduling->filter(function ($v) use ($open_card_m)
            {
            if ($open_card_m->processrename->rename == $v->process_name) {
                auditSave($v);
                }
            });
        return $pass;
        }
    protected function save()
        {
        $data = $this->repository->autosave(request()->toArray());
        if (isEmpty($data->sort)) {
            $data->sort = $data->id;
            $data->save();
            }
        return $data;
        }

    protected function deletePassByWip()
        {
        $request = request();
        $wip     = is_array($request->details) ? $request->details : json_decode($request->details, true);
        $ids     = array_map(function ($v)
            {
            return $v['id'];
            }, $wip);
        return $this->pass->deleteByWipIds($ids);
        }
    protected function delete()
        {

        return $this->pass->whereIn("id", $this->getRequestIds())->get()->map(function ($item)
            {
            return $this->pass->deletePass($item->id);
            });
        }
    }